package com.songshuai.pangu.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.songshuai.pangu.api.component.SalesMeetingComponent;
import com.songshuai.pangu.api.dto.pangu.*;
import com.songshuai.pangu.api.service.SalesMeetingService;
import com.songshuai.webapi.baseapi.dto.feign.request.pangu.salemeeting.QueryCustomersReqDto;
import com.songshuai.webapi.baseapi.dto.feign.request.pangu.salemeeting.SendInvitationReqDto;
import com.songshuai.webapi.baseapi.dto.feign.request.pangu.salemeeting.TalkNotesReqDto;
import com.songshuai.webapi.baseapi.dto.feign.response.pangu.salemeeting.*;
import com.songshuai.webapi.baseapi.dto.feign.response.pangu.salemeeting.SignInfoResDto;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.pojo.BaseParmDto;
import com.songshuai.webapi.baseapi.pojo.QueryPageRes;
import com.songshuai.webapi.baseapi.pojo.QueryRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: lhx
 * @Date: 2019/3/29 20:35
 */
@Slf4j
@Service
public class SalesMeetingServiceImpl implements SalesMeetingService {


    @Autowired
    private SalesMeetingComponent salesMeetingComponent;


    /**
     * 查看客户回执单信息
     * @param inviteNo 邀约编号
     * @return
     */
    @Override
    public ReceiptInfoResDto queryReceipt(String inviteNo) {
        log.info("查看客户回执单信息-请求参数：[{}]",inviteNo);
        String receipt = salesMeetingComponent.queryReceipt(inviteNo);
        log.info("查看客户回执单信息-盘古返回参数：[{}]",receipt);
        if (StringUtils.isNotBlank(receipt)){
            QueryRes<QueryReceiptByInviteNoResDto> queryRes = JSON.parseObject(receipt, new TypeReference<QueryRes<QueryReceiptByInviteNoResDto>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                if(null != queryRes.getResult()){
                    QueryReceiptByInviteNoResDto result = queryRes.getResult();
                    return new ReceiptInfoResDto(){{
                        setCustomerName(result.getCustomName());
                        setCustomerTel(result.getCustomTel());
                        setCompanionNum(result.getCompanionNum());
                        setIsFullAttend(result.getIsFullAttend());
                        setRoomStyleName(result.getRoomStyleName());
                        setTenants(result.getTenants());
                        setRoomCnt(result.getRoomCnt());
                        setTripModeName(result.getTripModeName());
                        setFlightOrTrainNum(result.getFlightOrTrainNum());
                        setStationName(result.getStationName());
                        setArriveTime(result.getArriveTime());
                        setTicketInfos(result.getPicList().stream().map(x -> x.getAddress()).collect(Collectors.toList()));
                        setRemark(result.getBack());
                    }};
                }
                return new ReceiptInfoResDto();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }


    /**
     * 查看邀请函
     * @param meetingCode 会议编号
     * @return
     */
    @Override
    public List<InvitationLetterResDto> queryInvitationLetter(String meetingCode) {
        log.info("查看邀请函-请求参数：[{}]",meetingCode);
        String letter = salesMeetingComponent.queryInvitationLetter(meetingCode);
        log.info("查看邀请函-盘古返回参数：[{}]",letter);
        if (StringUtils.isNotBlank(letter)){
            QueryRes<List<QueryMeetingInviteListResDto>> queryRes = JSON.parseObject(letter, new TypeReference<QueryRes<List<QueryMeetingInviteListResDto>>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                if(!CollectionUtils.isEmpty(queryRes.getResult())){
                    List<QueryMeetingInviteListResDto> result = queryRes.getResult();
                    return result.stream().map(x -> {
                        return new InvitationLetterResDto(){{
                            setMainKey(x.getMain_Key());
                            setPicName(x.getPicName());
                            setPicAddress(x.getPicAddress());
                            setPicSort(x.getPicSort());
                        }};
                    }).collect(Collectors.toList());
                }
                return new ArrayList<>();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }



    /**
     * 查询会议列表
     * @param dateType 0-最近 1-未来
     * @return
     */
    @Override
    public List<MeetingListResDto> queryMeetingList(Integer dateType, String userId) {
        log.info("查询会议列表-请求参数：dateType:[{}], userId:[{}]",dateType,userId);
        String meetingList = salesMeetingComponent.queryMeetingList(dateType,Integer.parseInt(userId));
        log.info("查询会议列表-盘古返回参数：[{}]",meetingList);
        if (StringUtils.isNotBlank(meetingList)){
            QueryRes<List<SaleMettingGetResDto>> queryRes = JSON.parseObject(meetingList, new TypeReference<QueryRes<List<SaleMettingGetResDto>>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                if(!CollectionUtils.isEmpty(queryRes.getResult())){
                    List<SaleMettingGetResDto> result = queryRes.getResult();
                    return result.stream().map(x -> {
                        return new MeetingListResDto(){{
                            setCode(x.getCode());
                            setChargeManTel(x.getChargeManTel());
                            setChargeManName(x.getChargeManName());
                            setTheme(x.getTheme());
                            setStarTime(x.getStarTime());
                            setEndTime(x.getEndTime());
                            setAddress(x.getAddress());
                            setLat(x.getLat());
                            setLng(x.getLng());
                            setAssistCnt(x.getAssistCnt());
                        }};
                    }).collect(Collectors.toList());
                }
                return new ArrayList<>();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }


    /**
     * 根据会议查询客户集合（已邀约）
     * @param saleId
     * @param meetingNo
     * @return
     */
    @Override
    public List<CustomerListResDto> queryCustomerList(Integer saleId, String meetingNo) {
        log.info("根据会议查询客户集合（已邀约）-请求参数：[{}]，[{}]",saleId,meetingNo);
        String customerList = salesMeetingComponent.queryCustomerList(saleId, meetingNo);
        log.info("根据会议查询客户集合（已邀约）-盘古返回参数：[{}]",customerList);
        if (StringUtils.isNotBlank(customerList)){
            QueryRes<List<SaleCustomerGetResDto>> queryRes = JSON.parseObject(customerList, new TypeReference<QueryRes<List<SaleCustomerGetResDto>>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                if(!CollectionUtils.isEmpty(queryRes.getResult())){
                    List<SaleCustomerGetResDto> result = queryRes.getResult();
                    return result.stream().map(x -> {
                        return new CustomerListResDto(){{
                            setMeetingNo(x.getMeetingNo());
                            setCustomerName(x.getCustomerName());
                            setCustomerTel(x.getCustomerTel());
                            setCustomerGuid(x.getCustomerGuid());
                            setClueGuid(x.getClueGuid());
                            setInviteNo(x.getInviteNo());
                            setIntentionGrade(x.getIntentionGrade());
                            setIntentionGradeName(x.getIntentionGradeName());
                            setIsBindWebchat(x.getIsBindWebchat());
                            setIntentionalProvince(x.getIntentionalProvince());
                            setIntentionalProvinceName(x.getIntentionalProvinceName());
                            setIntentionalCity(x.getIntentionalCity());
                            setIntentionalCityName(x.getIntentionalCityName());
                            setAttendStatus(x.getAttendstatus());
                            setAttendStatusName(x.getAttendstatusName());
                            setSignInfoRes(x.getLstSignInfo().stream().map(y ->{
                                return new SignInfoResDto(){{
                                    setSignStatus(y.getSignstatus());
                                    setSignStatusName(y.getSignstatusName());
                                    setSigntime(y.getSigntime());
                                }};
                            }).collect(Collectors.toList()));
                        }};
                    }).collect(Collectors.toList());
                }
                return new ArrayList<>();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }


    /**
     * 查询客户信息
     * @param request
     * @return
     */
    @Override
    public QueryPageRes<List<CustomerInfosResDto>> queryCustomers(BaseParmDto<QueryCustomersReqDto> request) {
        log.info("查询客户信息-请求参数：[{}]",JSON.toJSONString(request));
        String customers = salesMeetingComponent.queryCustomers(request);
        log.info("查询客户信息-盘古返回参数：[{}]",customers);
        if (StringUtils.isNotBlank(customers)){
            QueryRes<QueryPageRes<List<GetSaleCustomerList>>> queryRes = JSON.parseObject(customers, new TypeReference<QueryRes<QueryPageRes<List<GetSaleCustomerList>>>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                if (null != queryRes.getResult()){
                    QueryPageRes<List<GetSaleCustomerList>> result = queryRes.getResult();
                    if (!CollectionUtils.isEmpty(result.getBody())){
                        List<GetSaleCustomerList> body = result.getBody();
                        List<CustomerInfosResDto> collect = body.stream().map(x -> {
                            return new CustomerInfosResDto() {{
                                setCustomerName(x.getCustomerName());
                                setCustomerGuid(x.getCustomerGuid());
                                setClueGuid(x.getClueGuid());
                                setCity(x.getCity());
                                setGender(x.getGender());
                                setMainPhone(x.getMainPhone());
                                setProvince(x.getProvince());
                            }};
                        }).collect(Collectors.toList());
                        return QueryPageRes.setPageData(collect,result.getCount());
                    }
                }
                return QueryPageRes.setPageData(new ArrayList<>(),0l);
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }



    /**
     * 发送邀请函
     * @param request
     * @return
     */
    @Override
    public String sendInvitation(SendInvitationReqDto request) {
        log.info("发送邀请函-请求参数：[{}]",JSON.toJSONString(request));
        String invitation = salesMeetingComponent.sendInvitation(request);
        log.info("发送邀请函-盘古返回参数：[{}]",invitation);
        if (StringUtils.isNotBlank(invitation)){
            QueryRes<String> queryRes = JSON.parseObject(invitation, new TypeReference<QueryRes<String>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                if(StringUtils.isNotBlank(queryRes.getResult())){
                    return queryRes.getResult();
                }
                return "";
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }


    /**
     * 查询销售人员信息
     * @param userId
     * @return
     */
    @Override
    public List<SalesManInfoResDto> querySalesInfo(String userId) {
        log.info("查询销售人员信息-请求参数：[{}]",userId);
        String salesInfo = salesMeetingComponent.querySalesInfo(userId);
        log.info("查询销售人员信息-盘古返回参数：[{}]",salesInfo);
        if (StringUtils.isNotBlank(salesInfo)){
            QueryRes<List<QuerySalesInfoResDto>> queryRes = JSON.parseObject(salesInfo, new TypeReference<QueryRes<List<QuerySalesInfoResDto>>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                if (null != queryRes.getResult()){
                    List<QuerySalesInfoResDto> result = queryRes.getResult();
                    if (!CollectionUtils.isEmpty(result)){
                        return result.stream().map(x -> {
                            return new SalesManInfoResDto() {{
                                setUserid(x.getUserId());
                                setTruename(x.getTrueName());
                                setMobile(x.getMobile());
                            }};
                        }).collect(Collectors.toList());
                    }
                }
                return new ArrayList<>();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }



    /**
     * 转交客户
     * @param userId 用户id
     * @param cluesIds 线索GUID
     * @param saleIds 销售id
     * @return
     */
    @Override
    public Boolean handOverCustomer(String userId, List<Long> cluesIds, List<Integer> saleIds) {
        log.info("转交客户-请求参数：userId:[{}], cluesIds:[{}], saleIds:[{}]",userId,cluesIds,saleIds);
        String customer = salesMeetingComponent.handOverCustomer(userId, cluesIds, saleIds);
        log.info("转交客户-盘古返回参数：[{}]",customer);
        if (StringUtils.isNotBlank(customer)){
            QueryRes<Boolean> queryRes = JSON.parseObject(customer, new TypeReference<QueryRes<Boolean>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                return queryRes.getResult();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        log.info("转交客户-调用盘古失败，用户id：%s,线索GUID：%s,销售id：%s",userId,cluesIds,saleIds);
        return false;
    }


    /**
     * 新增沟通记录
     * @param request
     * @return
     */
    @Override
    public Boolean addTalkNotes(TalkNotesReqDto request) {
        log.info("新增沟通记录-请求参数：[{}]",JSON.toJSONString(request));
        String talkNotes = salesMeetingComponent.addTalkNotes(request);
        log.info("新增沟通记录-盘古返回参数：[{}]",talkNotes);
        if (StringUtils.isNotBlank(talkNotes)){
            QueryRes<Boolean> queryRes = JSON.parseObject(talkNotes, new TypeReference<QueryRes<Boolean>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                return queryRes.getResult();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return false;
    }


    /**
     * 获取客户历史沟通记录
     * @param clueGuid
     * @return
     */
    public List<CommunicateListResDto> getCommunicateList(Long clueGuid) {
        log.info("获取客户历史沟通记录-请求参数：[{}]",clueGuid);
        String communicateList = salesMeetingComponent.getCommunicateList(clueGuid);
        log.info("获取客户历史沟通记录-盘古返回参数：[{}]",communicateList);
        if (StringUtils.isNotBlank(communicateList)){
            QueryRes<List<GetCommunicateListResDto>> queryRes = JSON.parseObject(communicateList, new TypeReference<QueryRes<List<GetCommunicateListResDto>>>() {});
            if (ResultStatus.SUCCESS.getErrorCode() == queryRes.getStatus()){
                if (null != queryRes.getResult()){
                    List<GetCommunicateListResDto> result = queryRes.getResult();
                    if (!CollectionUtils.isEmpty(result)){
                        return result.stream().map(x -> {
                            return new CommunicateListResDto() {{
                                setId(x.getID());
                                setCustomGuid(x.getCustomGuid());
                                setClueGuid(x.getClueGuid());
                                setCommunicatContent(x.getCommunicatContent());
                                setCommunicater(x.getCommunicater());
                                setCommunicaterName(x.getCommunicaterName());
                                setCommunicatTime(x.getCommunicatTime());
                                setFileUrls(x.getFileUrls());
                            }};
                        }).collect(Collectors.toList());
                    }
                }
                return new ArrayList<>();
            }else {
                throw new BusinessException(queryRes.getInfo(),ResultStatus.FAILOfficial);
            }
        }
        return null;
    }


}
